﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace kaoshi
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {

            }
            else
            {
                FillData();
            }
        }

        private void FillData()
        {
            var luoxuan = "select * from Articles";

            var di = DbHelper.GetData(luoxuan);
            gv1.DataSource = di;
            gv1.DataBind();
        }

        protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var jia = Getvalue(e.RowIndex, 0);
            var yi = int.TryParse(jia, out int id);
            var Title = Getvalue(e.RowIndex, 1);
            var Content = Getvalue(e.RowIndex, 2);
            var Author = Getvalue(e.RowIndex, 3);
            var Remarks = Getvalue(e.RowIndex, 4);
            if(yi)
            {
                var sql = string.Format("update Articles set Title= '{0}',Content='{1}', Author='{2}',Remarks='{3}' where Id = '{4}'", Title,Content,Author, Remarks, id);
                DbHelper.SenYe(sql);

            }
            else
            {
               
                var sql = string.Format("insert into Articles(Title,Content,Author)values('{0}','{1}','{2}')",Title,Content,Author);
                DbHelper.SenYe(sql);
            }
            gv1.EditIndex = -1;
            FillData();
        }

        protected void gv1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gv1.EditIndex = -1;
            FillData();
        }

        protected void gv1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = Getvalue(e.RowIndex, 0);

            var sql = string.Format("delete from Articles where Id = {0}", id);
            DbHelper.SenYe(sql);
            gv1.EditIndex = -1;
            FillData();
        }

        public string Getvalue(int rowIndex, int colIndex)
        {
            var s = gv1.Rows[rowIndex].Cells[colIndex];
            var value = s.Controls.Count > 0 ? ((TextBox)s.Controls[0]).Text : s.Text;
            return value;
        }

        protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gv1.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void add_Click(object sender, EventArgs e)
        {
            var sql = "select * from Articles";
            var d = DbHelper.GetData(sql);
            var b = d.Copy();
            b.Rows.Add(b.NewRow());

            gv1.DataSource = b;
            gv1.DataBind();

            gv1.EditIndex = b.Rows.Count - 1;
            gv1.DataSource = b;
            gv1.DataBind();
        }
    }
}